/*
 * Copyright 2007 The JA-SIG Collaborative. All rights reserved. See license
 * distributed with this file and available online at
 * http://www.ja-sig.org/products/cas/overview/license/
 */
package com.maywide.jdp.system.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.Cache;
import org.jboss.cache.CacheFactory;
import org.jboss.cache.DefaultCacheFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.core.io.Resource;

import com.maywide.jdp.system.cache.RuleCacheListener;

/**
 * 
 * @author Scott Battaglia
 * @version $Revision: 1.5 $ $Date: 2011/04/02 18:37:15 $
 * @since 3.0.5
 *
 */
@SuppressWarnings("rawtypes")
public class JBossCacheFactory implements FactoryBean, InitializingBean, DisposableBean {
    
    private final Log log = LogFactory.getLog(this.getClass());
	private Cache<String, Object> cache;
	private Resource configLocation;
    
    public Object getObject() throws Exception {
        return this.cache;
    }

    public Class<Cache> getObjectType() {
        return Cache.class;
    }

    public boolean isSingleton() {
        return true;
    }

    public void afterPropertiesSet() throws Exception {
        final CacheFactory<String, Object> cf = new DefaultCacheFactory<String, Object>();
        this.cache = cf.createCache(this.configLocation.getInputStream());
        this.cache.addCacheListener(new RuleCacheListener());
        log.info("Starting TreeCache service.");
        this.cache.start();
    }

	public void destroy() throws Exception {
        log.info("Shutting down TreeCache service.");
        this.cache.destroy();
    }

	@Required
	public void setConfigLocation(Resource configLocation) {
	    this.configLocation = configLocation;
	}
}
